package com.supplychainapi.utils;

import com.alibaba.fastjson.JSONObject;
import com.supplychainapi.common.RestResponse;
import com.supplychainapi.domain.JwtSubjectEntity;
import com.supplychainapi.model.Tbuser;
import io.jsonwebtoken.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil
{
    @Value("${jwt.id}")
    private String JWT_ID;

    @Value("${jwt.secret}")
    private String JWT_SECRET;

    private int JWT_TTL = -1;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 由字符串生成加密key
     * @return
     */
    public SecretKey generalKey(){
        String stringKey = JWT_ID + JWT_SECRET;
        byte[] encodedKey = Base64.decodeBase64(stringKey);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 创建jwt
     * @param subject
     * @return
     * @throws Exception
     */
    public String createJWT(String subject) throws Exception {

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey key = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(JWT_ID)
                .setIssuedAt(now)
                .setSubject(subject)
                .signWith(signatureAlgorithm, key);
        // 配置过期时间
        if (JWT_TTL >= 0) {
            long expMillis = nowMillis + JWT_TTL;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }

    /**
     * 解密jwt
     * @param jwt
     * @return
     * @throws Exception
     */
    public Claims parseJWT(String jwt) throws Exception{
        SecretKey key = generalKey();
        Claims claims = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwt).getBody();
        return claims;
    }

    /**
     * 解析jwtSubject
     * @param jwt
     * @return
     * @throws Exception
     */
    public JwtSubjectEntity parseJWTSubject(String jwt) throws Exception{
        SecretKey key = generalKey();
        Claims claims = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwt).getBody();
        String subject = claims.getSubject();
        return JSONObject.parseObject(subject, JwtSubjectEntity.class);
    }

    /**
     * 生成subject信息
     * @param user
     * @return
     */
    public String generalSubject(Tbuser user){
        JSONObject jo = new JSONObject();
        jo.put("fsUserId", user.getFsUserId());
        jo.put("fsShopGUID", user.getFsShopGUID());
        return jo.toJSONString();
    }

    /**
     * 解析subject信息
     * @param subject
     * @return
     */
    public static JwtSubjectEntity parseSubject(String subject)
    {
        return JSONObject.parseObject(subject, JwtSubjectEntity.class);
    }

    public static String getJwtToken(HttpServletRequest request)
    {
        String jwtToken = "";
        // header 头中携带jwt token
        jwtToken = request.getHeader("jwt");
        if (jwtToken == null) {
            // 获取cookie中token
            jwtToken = CookieUtil.getJwtToken(request.getCookies());
        }
        // 如果token不存在
        if (StringUtils.isBlank(jwtToken)) {
            return "";
        }

        // 尝试解析,如果解析异常则表示,登录失效
//        try {
//            .parseJWT(jwtToken);
//        } catch (Exception e){
//            return "";
//        }

        return jwtToken;
    }
}